<?php
/**
 * Author: xx.com
 */ 
namespace Api\Controller;
use Home\Logic\GoodsLogic;
use Think\Page;
class IntegralController extends BaseController {
    
    /**
     * 析构流函数
     */
    public function  __construct() {   
        parent::__construct();    
    }
    
    /**
     * 获取积分商品分类列表
     */
    public function integralCategoryList(){        
       
        $integralCategoryList = M('integral_goods_category')->where("is_show=1")->order("sort_order desc")->limit(8)->select();
        foreach ($integralCategoryList as $key => $value) {
           $integralCategoryList[$key]['image'] = parseMediaUrl($value['image']);
        }
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$integralCategoryList );
        $json_str = json_encode($json_arr);            
        exit($json_str);
    }

    /**
     * 获取积分标签列表
     */
    public function integralLabelList(){
        $integralLabelNavList = M('integral_label')->where("type=1 and is_show=1 ")->order("sort_order desc")->limit(4)->select();
		$integralLabelList = M('integral_label')->where("type=2 and is_show=1 ")->order("sort_order desc")->limit(4)->select();
		// 对列表推荐标签查询商品 
		foreach($integralLabelList as $k => &$v){
			$where['ig.is_on_sale'] = 1;
			$where['igl.integral_label_id'] = $v['id'];
			$goods_list = M('integral_goods_label')->alias('igl')
			->join('__INTEGRAL_GOODS__ AS ig ON ig.goods_id = igl.integral_goods_id ')->where($where)->order("ig.sort desc")->limit(3)->select();
			foreach($goods_list as $ks => &$vs){
				$vs['original_img'] = parseMediaUrl($vs['original_img']);
			}
			$v['goods_list'] = $goods_list;
		}
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>['integralLabelList'=>$integralLabelList,'integralLabelNavList'=>$integralLabelNavList] );
        $json_str = json_encode($json_arr);            
        exit($json_str);
    }
    
    /**
     * 商品列表页
     */
    public function goodsList(){
        $p = I('p', 1, 'intval');// 当前页码
		$category_id = I('category_id'); // 当前分类id
		$label_id = I('label_id'); // 当前分类id
		$goods_id = I('goods_id'); // 当前单独商品
		
		$where['ig.is_on_sale'] = 1;
		if($label_id)$where['igl.integral_label_id'] = intval($label_id);
		if($category_id)$where['igc.id'] = intval($category_id);
		if($goods_id)$where['ig.goods_id'] = intval($goods_id);
		
		$goods_list = M('integral_goods')->alias('ig')
		->join('__INTEGRAL_GOODS_CATEGORY__ AS igc ON ig.cat_id = igc.id ')
		->join('LEFT JOIN __INTEGRAL_GOODS_LABEL__ AS igl ON ig.goods_id = igl.integral_goods_id ')
		->field('ig.*,igc.name as category_name,igc.image as category_image,ig.content')
		->where($where)->order("ig.sort desc")->page($p,10)->select();
		foreach($goods_list as $k => &$v){
			$v['category_image'] = parseMediaUrl($v['category_image']);
			$v['original_img'] = parseMediaUrl($v['original_img']);
			$v['content'] = parseRichTextContent($v['content']);
		}
		if($goods_id && count($goods_list) == 1)$goods_list = $goods_list[0];
			
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$goods_list );
        $json_str = json_encode($json_arr,true);            
        exit($json_str);
    }
	
	/**
	 * 商品列表页
	 */
	public function goodsInfo(){
		$goods_id = I('goods_id'); // 当前单独商品
		
		$where['ig.is_on_sale'] = 1;
		if($goods_id)$where['ig.goods_id'] = intval($goods_id);
		
		$goods_list = M('integral_goods')->alias('ig')
		->join('LEFT JOIN __INTEGRAL_GOODS_CATEGORY__ AS igc ON ig.cat_id = igc.id ')
		->join('LEFT JOIN __INTEGRAL_GOODS_LABEL__ AS igl ON ig.goods_id = igl.integral_goods_id ')
		->field('ig.*,igc.name as category_name,igc.image as category_image,ig.content')
		->where($where)->order("ig.sort desc")->find();
		if(!$goods_list){
			$this->returnInfo(-1,"无此商品");
		}
		$goods_list['category_image'] = parseMediaUrl($goods_list['category_image']);
		$goods_list['original_img'] = parseMediaUrl($goods_list['original_img']);
		$goods_list['content'] = parseRichTextContent($goods_list['content']);
	    $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$goods_list );
	    $json_str = json_encode($json_arr,true);            
	    exit($json_str);
	}
	
	/**
	 * 商品购买核对
	 */
	public function purchaseCheck(){
		$goods_id = I('goods_id',0,'intval'); // 当前单独商品
		$usersInfo = get_user_info($this->user_id);  // 用户
		if ($this->user_id == 0) exit(json_encode(array('status' => -1, 'msg' => '用户user_id不能为空', 'result' => '')));

		// 收货地址
		$addresslist = M('UserAddress')
		->where(["user_id"=>$this->user_id])
		->order("is_default desc")
		->limit(1)
		->select();
		
		// 获取商品信息
		$where['ig.is_on_sale'] = 1;
		if($goods_id)$where['ig.goods_id'] = intval($goods_id);
		
		$goods_list = M('integral_goods')->alias('ig')
		->join('__INTEGRAL_GOODS_CATEGORY__ AS igc ON ig.cat_id = igc.id ')
		->join('LEFT JOIN __INTEGRAL_GOODS_LABEL__ AS igl ON ig.goods_id = igl.integral_goods_id ')
		->field('ig.*,igc.name as category_name,igc.image as category_image,ig.content')
		->where($where)->order("ig.sort desc")->page($p,10)->select();
		foreach($goods_list as $k => &$v){
			$v['category_image'] = parseMediaUrl($v['category_image']);
			$v['original_img'] = parseMediaUrl($v['original_img']);
			$v['content'] = parseRichTextContent($v['content']);
		}
		if(count($goods_list) <= 0) exit(json_encode(array('status' => -1, 'msg' => '无此商品信息', 'result' => '')));
		if($goods_id && count($goods_list) == 1)$goods_list = $goods_list[0];
		
		$json_arr = array(
		    'status' => 1,
		    'msg' => '获取成功',
		    'result' => array(
		        'addressList' => $this->getAddressInfo($addresslist), // 收货地址
		        'goodsList' => $goods_list, // 商品信息
		        'userInfo' => $usersInfo?$usersInfo:[], // 用户详情
		    )
		);
		exit(json_encode($json_arr));
	}
	/**
	 * 积分商品下单
	 */
	public function buyGoods(){
		// 检测商品状态
		$goods_id = I('goods_id',0,'intval'); // 当前单独商品
		$address_id = I('address_id', 0, 'intval');
		$usersInfo = get_user_info($this->user_id);  // 用户
		if ($this->user_id == 0) exit(json_encode(array('status' => -1, 'msg' => '用户user_id不能为空', 'result' => '')));
		
		// 获取商品信息
		$where['ig.is_on_sale'] = 1;
		if($goods_id)$where['ig.goods_id'] = intval($goods_id);
		
		$goods_list = M('integral_goods')->alias('ig')
		->join('__INTEGRAL_GOODS_CATEGORY__ AS igc ON ig.cat_id = igc.id ')
		->join('LEFT JOIN __INTEGRAL_GOODS_LABEL__ AS igl ON ig.goods_id = igl.integral_goods_id ')
		->field('ig.*,igc.name as category_name,igc.image as category_image,ig.content')
		->where($where)->order("ig.sort desc")->page($p,10)->select();
		foreach($goods_list as $k => &$v){
			$v['category_image'] = parseMediaUrl($v['category_image']);
			$v['original_img'] = parseMediaUrl($v['original_img']);
			$v['content'] = parseRichTextContent($v['content']);
		}
		if(count($goods_list) <= 0) exit(json_encode(array('status' => -1, 'msg' => '无此商品信息', 'result' => '')));
		if($goods_id && count($goods_list) == 1)$goods_list = $goods_list[0];
		// 检测积分状态
		// p($goods_list);die;
		if($usersInfo['pay_points'] < $goods_list['integral_count']){
			exit(json_encode(array('status' => -1, 'msg' => '积分不足', 'result' => '')));
		}
		if($address_id < 1 ){
			$this->returnInfo(-1,"请填写收货地址");
		}
		$address = M('UserAddress')->where([
		    "address_id" => $address_id
		])->find();
		$order_sn = 'M' . $this->_createOrderSN();
		// 开启事务 下订单扣积分
		$Model = M();
		$Model->startTrans();
		// 添加订单
		// p($address);die;
		$addOrder['goods_id'] = $goods_id;// 订单编号
		$addOrder['order_sn'] = $order_sn;// 订单编号
		$addOrder['user_id'] = $this->user_id;// 用户id
		$addOrder['order_status'] = 1;// 订单状态
		$addOrder['shipping_status'] = 0;// 发货状态
		$addOrder['pay_status'] = 1;// 支付状态
		$addOrder['consignee'] = $address['consignee'];// 收货人
		$addOrder['country'] = $address['country'];// 国家
		$addOrder['province'] = $address['province'];// 省份id
		$addOrder['city'] = $address['city'];// 城市id
		$addOrder['district'] = $address['district'];// 县
		$addOrder['twon'] = $address['twon'];// 街道
		$addOrder['address'] = $address['address'];// 详细地址
		$addOrder['zipcode'] = $address['zipcode'];// 邮编
		$addOrder['mobile'] = $address['mobile'];// 手机
		$addOrder['integral'] = $goods_list['integral_count'];// 使用积分
		$addOrder['add_time'] = time();// 下单时间
		$addOrder['shipping_time'] = 0;// 最后新发货时间
		$addOrder['confirm_time'] = 0;// 收货确认时间
		$addOrder['pay_time'] = time();// 支付时间
		$addOrder['user_note'] = '';// 用户备注
		$addOrder['admin_note'] = '';// 管理员备注
		$orderRes = $Model->table('__INTEGRAL_ORDER__')->add($addOrder);
		// 订单扣款
		$log = accountLog($this->user_id, 0, -1 * $goods_list['integral_count'], '购买积分商品' . $addOrder['order_sn'], 0, $orderRes['order_id'], $addOrder['order_sn']);
		
		if($orderRes && $log){
			$Model->commit();
			$this->returnInfo(1,"商品购买成功，请等待发货！");
		}else{
			$Model->rollback();
			$this->returnInfo(-1,"购买失败");
		}
	}
	
	// 生成订单号
	public function _createOrderSN()
	{
		return date('YmdHis', time()) . '' . $this->randNumber();
	}

	/**
	 * 获取随机位数数字
	 * @param integer $len 长度
	 * @return string
	 */
	public function randNumber($len = 4)
	{
		$chars = str_repeat('0123456789', 10);
		$chars = str_shuffle($chars);
		$str = substr($chars, 0, $len);
		return $str;
	}
	
	
}